using System.Drawing;
using System.Net.Http;
using CoreGraphics;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using UIKit;

namespace libmp
{
    public static partial class Util
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();
        public static UIKit.UIColor MainColor = UIKit.UIColor.FromRGB(251, 114, 153);
        public static UIKit.UIColor MainBKColor = UIKit.UIColor.FromRGB(244, 244, 244);
        public static UIImage UIImageFromHotFile(string path)
        {
            return UIImage.FromFile($"{App.HotStorageRoot}/res/{path}");
        }
        public static UISearchBar createMySearchBar(float Width, string placeholder, UIColor textUIcolor, UIImage clearImg, UIImage leftAskImg, UIFont textFont, UIColor backgroundColor)
        {
            var searchBar = new UISearchBar();
            searchBar.Placeholder = "输入关键字查找";
            searchBar.BackgroundColor = backgroundColor;
            searchBar.BarTintColor = backgroundColor;
            searchBar.AutocapitalizationType = UITextAutocapitalizationType.None;
            searchBar.AutocorrectionType = UITextAutocorrectionType.No;

            //文本框颜色，字体
            var uiTextField = (UITextField) searchBar.ValueForKey(new NSString("_searchField"));
            uiTextField.BackgroundColor = backgroundColor;
            uiTextField.TextColor = textUIcolor;
            uiTextField.Font = textFont;
            uiTextField.BorderStyle = UITextBorderStyle.None;

            //文本框的光标颜色
            uiTextField.TintColor = textUIcolor;

            //文本框的占位文字颜色
            uiTextField.AttributedPlaceholder = new NSAttributedString(placeholder, new UIStringAttributes()
            {
                ForegroundColor = textUIcolor.ColorWithAlpha(0.5f),
            });
            // uiTextField.LeftViewMode = UITextFieldViewMode.Never;
            // uiTextField.RightViewMode = UITextFieldViewMode.UnlessEditing;

            logger.Log("--------------------------");
            //清除按钮
            searchBar.SetImageforSearchBarIcon(new UIImage(clearImg.CGImage, 2, UIImageOrientation.Up), UISearchBarIcon.Clear, UIControlState.Normal);

            //左侧问号按钮
            searchBar.SetImageforSearchBarIcon(new UIImage(leftAskImg.CGImage, 2, UIImageOrientation.Up), UISearchBarIcon.Search, UIControlState.Normal);

            return searchBar;
        }

        public static UIView createPopView(float width, float height)
        {
            var btnPicWidth = 18;
            var btnPicHeight = 18;
            var popView = new UIView();
            popView.Frame = new CGRect(0, 0, width, 320);
            popView.Layer.CornerRadius = 5;
            popView.ClipsToBounds = true;
            popView.Layer.BorderWidth = 0;
            var topView = new UIView();
            topView.SetParent(popView);
            topView.BackgroundColor = UIColor.White;
            topView.MakeConstraints(m =>
            {
                m.Left.EqualTo(popView);
                m.Top.EqualTo(popView);
                m.Height.EqualTo(NSObject.FromObject(popView.Frame.Height * 0.4));
                m.Width.EqualTo(NSObject.FromObject(popView.Frame.Width));
            });
            var topView1 = new UIView();
            topView1.Frame = new CGRect(10, 10, width - 20, btnPicWidth);
            topView1.SetParent(topView);

            var backButton = new UIButton();
            backButton.SetParent(topView1);
            backButton.Frame = new CGRect(0, 0, btnPicWidth * 2, btnPicHeight);
            var backImageViewButton = new UIImageView();
            var imgBack = UIImage.FromFile($"{App.HotStorageRoot}/res/popup/btn_back.png");
            backImageViewButton.Image = new UIImage(imgBack.CGImage, 2, UIImageOrientation.Up);
            backImageViewButton.SetParent(topView1);
            backImageViewButton.Frame = new CGRect(0, 0, btnPicWidth / 2, btnPicHeight);
            //backImageViewButton.MakeConstraints(m => m.Edges.EqualTo(backButton));
            backButton.TouchUpInside += delegate
            {
                MyPopupManager.HidePopView();
            };

            var closeButton = new UIButton();
            closeButton.SetParent(topView1);
            closeButton.Frame = new CGRect(topView1.Frame.Width - btnPicWidth * 2, 0, btnPicWidth * 2, btnPicHeight);
            var closeImageViewButton = new UIImageView();
            var imgClose = UIImage.FromFile($"{App.HotStorageRoot}/res/popup/btn_close.png");
            closeImageViewButton.Image = new UIImage(imgClose.CGImage, 2, UIImageOrientation.Up);
            closeImageViewButton.SetParent(topView1);
            closeImageViewButton.Frame = new CGRect(topView1.Frame.Width - btnPicWidth, 0, btnPicWidth, btnPicHeight);
            //closeImageViewButton.MakeConstraints(m => m.Edges.EqualTo(closeButton));
            closeButton.TouchUpInside += delegate
            {
                MyPopupManager.HidePopView();
            };

            var icoImageView = new UIImageView();
            var imgIco = UIImage.FromFile($"{App.HotStorageRoot}/res/popup/em_bad.png");
            icoImageView.Image = new UIImage(imgIco.CGImage, 2, UIImageOrientation.Up);
            icoImageView.SetParent(topView);
            icoImageView.MakeConstraints(m =>
            {
                m.Top.EqualTo(topView1.Bottom());
                m.Left.EqualTo(NSObject.FromObject((popView.Frame.Width - 60) / 2));
                m.Height.EqualTo(NSObject.FromObject(60));
                m.Width.EqualTo(NSObject.FromObject(60));
            });

            var topLabel = new UILabel();
            topLabel.SetParent(topView);
            topLabel.Frame = new CGRect(0, btnPicHeight + 70, popView.Frame.Width, 30);
            topLabel.TextAlignment = UITextAlignment.Center;
            topLabel.Text = "您当日的点播次数已经用完";
            topLabel.Font = UIFont.BoldSystemFontOfSize(14);
            topLabel.TextColor = Util.MainColor;

            var bottomView = new UIView();
            bottomView.SetParent(popView);
            bottomView.BackgroundColor = Util.MainColor;
            bottomView.MakeConstraints(m =>
            {
                m.Left.EqualTo(popView);
                m.Top.EqualTo(topView.Bottom());
                m.Height.EqualTo(NSObject.FromObject(popView.Frame.Height * 0.6));
                m.Width.EqualTo(NSObject.FromObject(popView.Frame.Width));
            });

            var bottomLabel1 = new UILabel();
            bottomLabel1.SetParent(bottomView);
            bottomLabel1.Frame = new CGRect(10, 5, popView.Frame.Width, 25);
            bottomLabel1.TextAlignment = UITextAlignment.Left;
            bottomLabel1.Text = "邀请好友观看，增加永久观看次数";
            bottomLabel1.Font = UIFont.BoldSystemFontOfSize(14);
            bottomLabel1.TextColor = UIColor.White;

            var bottomLabel2 = new UILabel();
            bottomLabel2.SetParent(bottomView);
            bottomLabel2.Frame = new CGRect(10, 30, popView.Frame.Width, 25);
            bottomLabel2.TextAlignment = UITextAlignment.Left;
            bottomLabel2.Text = "每邀请1个好友安装 = 永久增加每日播放次数1次。";
            bottomLabel2.TextColor = UIColor.White;
            bottomLabel2.Font = UIFont.SystemFontOfSize(12);

            var myCGRect = new CGRect((popView.Frame.Width - 150) / 2, 60, 150, 30);
            var backgroundColor = UIColor.White;
            var fontColor = Util.MainColor;
            var myFont = UIFont.BoldSystemFontOfSize(13);
            var shapeFirendButton = createMyButton(myCGRect, backgroundColor, fontColor, "邀请好友观看", myFont, true);
            shapeFirendButton.SetParent(bottomView);
            shapeFirendButton.TouchUpInside += (s, e) =>
            {
                logger.Log("邀请好友");
                // User.me.viewsNums++;
                User.me.Save();
                //此处通讯服务器更改剩余观看次数
                // UpdateViewNums(User.me.id, User.me.viewsNums, true);
            };

            var bottomLabel3 = new UILabel();
            bottomLabel3.SetParent(bottomView);
            bottomLabel3.Frame = new CGRect(10, 95, popView.Frame.Width, 25);
            bottomLabel3.TextAlignment = UITextAlignment.Left;
            bottomLabel3.Text = "购买VIP会员";
            bottomLabel3.Font = UIFont.BoldSystemFontOfSize(14);
            bottomLabel3.TextColor = UIColor.White;

            var bottomLabel4 = new UILabel();
            bottomLabel4.SetParent(bottomView);
            bottomLabel4.Frame = new CGRect(10, 120, popView.Frame.Width, 25);
            bottomLabel4.TextAlignment = UITextAlignment.Left;
            bottomLabel4.Text = "4大至尊特权，享受极速播放体验";
            bottomLabel4.TextColor = UIColor.White;
            bottomLabel4.Font = UIFont.SystemFontOfSize(12);

            var myCGRect1 = new CGRect((popView.Frame.Width - 150) / 2, 150, 150, 30);
            var buyVipButton = createMyButton(myCGRect1, backgroundColor, fontColor, "购买VIP会员", myFont, true);
            buyVipButton.SetParent(bottomView);
            buyVipButton.TouchUpInside += (s, e) =>
            {
                logger.Log("购买VIP会员");
            };
            return popView;
        }

        public static UIButton createMyButton(CGRect myCGRect, UIColor backgroundColor, UIColor fontColor, string btnString, UIFont myfont, bool ifFillet)
        {
            var myButton = new UIButton();
            myButton.Frame = myCGRect;
            myButton.BackgroundColor = backgroundColor;
            if (ifFillet)
            {
                myButton.Layer.CornerRadius = 5;
                myButton.ClipsToBounds = true;
                myButton.Layer.BorderWidth = 0;
            }

            var btnLabel = new UILabel();
            btnLabel.SetParent(myButton);
            btnLabel.TextColor = fontColor;
            btnLabel.Text = btnString;
            btnLabel.Font = myfont;
            btnLabel.MakeConstraints(m => m.Edges.EqualTo(myButton));
            btnLabel.TextAlignment = UITextAlignment.Center;

            return myButton;
        }

        public static void UpdateViewNums(string id, int viewsNums, bool changeMax)
        {
            var baseUrl = App.CurrentServerUrl;
            var body = LitJson.JsonMapper.ToJson(new { id = id, viewsNums = viewsNums, changeMax = changeMax });
            var url = $"http://{baseUrl}/user/updateViewNums";
            var res = Http.MakeRequest(new Http.Option
            {
                Url = url,
                    Method = HttpMethod.Post,
                    Body = body,
                    OnFinish = (ok, code, msg) =>
                    {
                        logger.Log("msg:" + msg);
                        if (code == 500)
                        {
                            logger.Log("----更新错误");
                        }
                        else
                        {
                            logger.Log("----更新成功");
                        }

                    },
                    OnProgress = (total, now) =>
                    {
                        logger.Log("progress", total, now);
                    }
            });
        }

        // public static void createAdverse(DataStore.OnlineConfig.AdImage adImg, UIView adverisePicView)
        // {
        //     var imgView = new UIImageView();
        //     mb.iOS.Util.SetUIImageViewUrl(imgView, adImg.imgpath);
        //     imgView.SetParent(adverisePicView);
        //     imgView.MakeConstraints(m => m.Edges.EqualTo(adverisePicView));
        //     var imgButton = new UIButton();
        //     imgButton.SetParent(adverisePicView);
        //     imgButton.MakeConstraints(m => m.Edges.EqualTo(adverisePicView));
        //     imgButton.TouchUpInside += (s, e) =>
        //     {
        //         logger.Log("点击====>" + adImg.imgid);
        //         Xamarin.Essentials.Browser.OpenAsync(adImg.imghref, Xamarin.Essentials.BrowserLaunchMode.External);
        //         User.me.Notify("clickad", LitJson.JsonMapper.ToJson(new { imgid = adImg.imgid }));
        //     };
        // }

    }

    namespace MyExtensions
    {
        using System.Collections.Generic;
        using System;
        using AVFoundation;
        using CoreGraphics;

        public static partial class MyExtensions
        {
            public static IEnumerable<T> OfType<T>(this IEnumerable<UIView> views) where T : UIView
            {
                List<T> response = new List<T>();
                foreach (var view in views)
                {
                    if (view.GetType() == typeof(T))
                    {
                        response.Add((T) view);
                    }
                }
                return response;
            }

            public static UIColor Darker(this UIColor c, float per)
            {
                nfloat r, g, b, a;
                c.GetRGBA(out r, out g, out b, out a);
                return UIColor.FromRGBA(r * per, g * per, b * per, a);
            }
        }

    }
}